package com.icoolkj.ms.pay.service.impl;

import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.request.AlipayTradeCloseRequest;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.icoolkj.ms.pay.service.PayService;
import com.icoolkj.ms.api.pay.model.PayOrder;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service("alipayService")
public class AlipayServiceImpl implements PayService {

    @Value("${alipay.appId}")
    private String appId;

    @Value("${alipay.privateKey}")
    private String privateKey;

    @Value("${alipay.publicKey}")
    private String publicKey;

    @Value("${alipay.notifyUrl}")
    private String notifyUrl;

    @Value("${alipay.returnUrl}")
    private String returnUrl;

    @Value("${alipay.gatewayUrl}")
    private String gatewayUrl;

    private AlipayClient alipayClient;

    public AlipayServiceImpl() {
        // 初始化AlipayClient
        this.alipayClient = new DefaultAlipayClient(gatewayUrl, appId, privateKey, 
            "json", "UTF-8", publicKey, "RSA2");
    }

    @Override
    public Map<String, String> createOrder(PayOrder payOrder) {
        try {
            AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
            request.setNotifyUrl(notifyUrl);
            request.setReturnUrl(returnUrl);

            // 构建请求参数
            Map<String, Object> bizContent = new HashMap<>();
            bizContent.put("out_trade_no", payOrder.getOrderNo());
            bizContent.put("total_amount", payOrder.getAmount().toString());
            bizContent.put("subject", payOrder.getSubject());
            bizContent.put("product_code", "FAST_INSTANT_TRADE_PAY");

            request.setBizContent(JSONUtil.toJsonStr(bizContent));

            // 调用支付宝接口
            String form = alipayClient.pageExecute(request).getBody();
            
            Map<String, String> result = new HashMap<>();
            result.put("orderNo", payOrder.getOrderNo());
            result.put("form", form);
            return result;
        } catch (Exception e) {
            log.error("创建支付宝支付订单失败", e);
            throw new RuntimeException("创建支付订单失败");
        }
    }

    @Override
    public boolean handlePayNotify(String payType, Map<String, String> params) {
        try {
            // TODO: 验证签名
            // 解析支付结果通知
            // 更新订单状态
            return true;
        } catch (Exception e) {
            log.error("处理支付宝支付回调失败", e);
            return false;
        }
    }

    @Override
    public PayOrder queryOrder(String orderNo) {
        try {
            AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
            Map<String, Object> bizContent = new HashMap<>();
            bizContent.put("out_trade_no", orderNo);
            request.setBizContent(JSONUtil.toJsonStr(bizContent));

            // TODO: 解析响应结果
            return null;
        } catch (Exception e) {
            log.error("查询支付宝订单失败", e);
            throw new RuntimeException("查询支付订单失败");
        }
    }

    @Override
    public boolean closeOrder(String orderNo) {
        try {
            AlipayTradeCloseRequest request = new AlipayTradeCloseRequest();
            Map<String, Object> bizContent = new HashMap<>();
            bizContent.put("out_trade_no", orderNo);
            request.setBizContent(JSONUtil.toJsonStr(bizContent));

            // TODO: 解析响应结果
            return true;
        } catch (Exception e) {
            log.error("关闭支付宝订单失败", e);
            return false;
        }
    }

    @Override
    public boolean refund(String orderNo, String refundReason) {
        try {
            AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
            Map<String, Object> bizContent = new HashMap<>();
            bizContent.put("out_trade_no", orderNo);
            bizContent.put("refund_reason", refundReason);
            request.setBizContent(JSONUtil.toJsonStr(bizContent));

            // TODO: 解析响应结果
            return true;
        } catch (Exception e) {
            log.error("支付宝退款失败", e);
            return false;
        }
    }
} 